package com.lyons.easyweb.modular.user;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyons.easyweb.core.util.Constant;
import com.lyons.easyweb.core.util.LayuiPageInfo;
import com.lyons.easyweb.exception.BaseResponseCode;
import com.lyons.easyweb.exception.BusinessException;
import com.lyons.easyweb.modular.user.pojo.SysUser;
import com.lyons.easyweb.modular.user.service.UserService;
import com.lyons.easyweb.modular.user.vo.req.UserReqVo;
import com.lyons.easyweb.modular.user.vo.resp.LoginRespVo;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.SecureUtil;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author HengDuCms
 * @since 2021-06-27
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	public LayuiPageInfo login(@Valid UserReqVo userReqVo, HttpSession session) {

		LoginRespVo user = userService.login(userReqVo);
		session.setAttribute(Constant.LOGIN_USER, user);
		if (ObjectUtils.isEmpty(user)) {
			return LayuiPageInfo.fail("登录失败 !");
		}

		return LayuiPageInfo.ok("登录成功 !");
	}

	@RequestMapping("/out")
	public void out(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		session.removeAttribute(Constant.LOGIN_USER);
		response.sendRedirect("/page/login.html");
//		request.getRequestDispatcher("/page/login.html").forward(request, response);
	}

	@RequestMapping("/updatePassword")
	public void updatePassword(String oldPassword, String newPassword, String againPassword, HttpServletResponse response, HttpServletRequest request) throws IOException {
		System.out.println(oldPassword);
		System.out.println(newPassword);
		System.out.println(againPassword);

		if (!newPassword.equalsIgnoreCase(againPassword)) {
			throw new BusinessException(4000, "新密码，两次密码不一致!");
		}

		LoginRespVo user = (LoginRespVo) request.getSession().getAttribute(Constant.LOGIN_USER);

		boolean result = userService.updatePwd(oldPassword, newPassword, user.getUserId());
		if (result) {
			request.getSession().removeAttribute(Constant.LOGIN_USER);
			response.sendRedirect("/page/login.html");
		}
	}

	@RequestMapping("/resetPwd")
	public LayuiPageInfo resetPassword(String userid) {

		userService.restPassword(userid);

		return LayuiPageInfo.ok("重置密码成功，新密码为系统默认密码 !");
	}

	// 查询所有
	@RequestMapping("/list")
	public LayuiPageInfo list(
			@RequestParam(value = "realName", required = false) String realName, 
			@RequestParam(value = "nickName", required = false) String nickName, 
			@RequestParam(value = "account", required = false) String account,
			@RequestParam(value = "page", defaultValue = "1") Integer current, 
			@RequestParam(value = "limit", defaultValue = "20") Integer limit) {

		IPage<SysUser> page = new Page<SysUser>(current, limit);

		QueryWrapper<SysUser> queryWrSysUserer = new QueryWrapper<SysUser>();

		if (!ObjectUtils.isEmpty(realName)) {
			queryWrSysUserer.lambda().like(SysUser::getRealName, realName);
		}
		if (!ObjectUtils.isEmpty(nickName)) {
			queryWrSysUserer.lambda().like(SysUser::getNickName, nickName);
		}
		if (!ObjectUtils.isEmpty(account)) {
			queryWrSysUserer.lambda().like(SysUser::getAccount, nickName);
		}

		queryWrSysUserer.lambda().orderByDesc(SysUser::getSort).orderByDesc(SysUser::getCreateTime);

		IPage<SysUser> ipage = userService.page(page, queryWrSysUserer);
		return LayuiPageInfo.ok(ipage.getTotal(), ipage.getRecords());
	}

	// 添加或者修改
	@RequestMapping("/saveOrUpdate")
	public LayuiPageInfo saveOrUpdate(@RequestBody @Valid SysUser sysUser) {

		if (ObjectUtils.isEmpty(sysUser.getId())) {
			
			if (ObjectUtils.isEmpty(sysUser.getPassword())) {
				return LayuiPageInfo.fail("密码不能够为空 !");
			} else {
				sysUser.setPassword(SecureUtil.md5(sysUser.getPassword()));
				sysUser.setSalt(UUID.randomUUID().toString());
			}

		} else {

		}

		userService.saveOrUpdate(sysUser);
		return LayuiPageInfo.ok("数据保存成功 !");
	}

	// 查询详情
	@RequestMapping("/findById")
	public LayuiPageInfo findById(String id) {
		return LayuiPageInfo.ok(userService.getById(id));
	}

	// 修改状态
	@RequestMapping("/status")
	public LayuiPageInfo status(String id, boolean status) {

		SysUser bean = userService.getById(id);
		if (ObjectUtils.isEmpty(bean)) {
			throw new BusinessException(BaseResponseCode.DATA_ID_EMPTY);
		}
		if (status) {
			bean.setStatus(1);
		} else {
			bean.setStatus(0);
		}
		userService.updateById(bean);
		return LayuiPageInfo.ok("状态修改成功 !");
	}

	// 查询所有（指定列）
	@RequestMapping("/listAll")
	public LayuiPageInfo listAll() {

		List<SysUser> list = userService.list(new QueryWrapper<SysUser>().lambda().select(SysUser::getId, SysUser::getRealName));
		return LayuiPageInfo.ok(list);
	}

	// 按照ID删除
	@RequestMapping("/delete")
	public LayuiPageInfo delete(String id) {

		userService.removeById(id);
		return LayuiPageInfo.ok("数据删除成功 !");
	}

	// 批量删除
	@RequestMapping("/batchDelete")
	public LayuiPageInfo batchDelete(@RequestBody String ids) {

		List<String> idList = Arrays.asList(ids.split(",")).stream().map(e -> {
			if (!ObjectUtils.isEmpty(e)) {
				return e;
			}
			return null;
		}).collect(Collectors.toList());

		userService.removeByIds(idList);
		return LayuiPageInfo.ok("成功删除了 [ " + idList.size() + " ] 条数据 ！");
	}

	// 删除所有
	@RequestMapping("/deleteAll")
	public LayuiPageInfo deleteAll() {

		userService.remove(new QueryWrapper<SysUser>());
		return LayuiPageInfo.ok("成功删除表中所有数 !");
	}

}